<template>
    <div class="common-layout">
        <el-container>
            <el-main style="padding-bottom: 80px;">
                <el-form ref="customerFormRef" :model="customerForm" :rules="rules" label-width="120px">
                    <!-- 基础信息 -->
                    <el-card style="margin-bottom: 20px;">
                        <template #header>
                            <span style="font-weight: bold;">编辑客户</span>
                        </template>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="客户编码" prop="customerCode">
                                    <el-input v-model="customerForm.customerCode" placeholder="请输入客户编码" readonly />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="客户名称" prop="customerName">
                                    <el-input v-model="customerForm.customerName" placeholder="请输入客户名称" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="所属行业" prop="industryId">
                                    <el-select v-model="customerForm.industryId" placeholder="请选择所属行业"
                                        style="width: 100%">
                                        <el-option v-for="item in industryList" :key="item.industryId"
                                            :label="item.industryName" :value="item.industryId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="客户来源" prop="customerSourceId">
                                    <el-select v-model="customerForm.customerSourceId" placeholder="请选择客户来源"
                                        style="width: 100%">
                                        <el-option v-for="item in customerSourceList" :key="item.customerSourceId"
                                            :label="item.customerSourceName" :value="item.customerSourceId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="联系人" prop="customerContact">
                                    <el-input v-model="customerForm.customerContact" placeholder="请输入联系人" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系电话" prop="contactPhone">
                                    <el-input v-model="customerForm.contactPhone" placeholder="请输入联系电话" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="电子邮箱" prop="customerEmail">
                                    <el-input v-model="customerForm.customerEmail" placeholder="请输入电子邮箱" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="销售部门" prop="organizationId">
                                    <el-input v-model="customerForm.organizationName" placeholder="请选择销售部门" readonly
                                        @click="openOrgDialog">
                                        <template #suffix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="销售负责人" prop="userId">
                                    <el-input v-model="customerForm.userName" placeholder="请选择销售负责人" readonly
                                        @click="openUserDialog">
                                        <template #suffix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="客户状态" prop="customerState">
                                    <el-radio-group v-model="customerForm.customerState">
                                        <el-radio :label="0">启用</el-radio>
                                        <el-radio :label="1">停用</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="客户地址" prop="contactAddress">
                                    <el-input v-model="customerForm.contactAddress" placeholder="请输入客户地址" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="备注" prop="customerNote">
                                    <el-input v-model="customerForm.customerNote" type="textarea" :rows="4"
                                        placeholder="请输入备注信息" maxlength="500" show-word-limit />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <!-- 财务信息 -->
                    <el-card style="margin-bottom: 20px;">
                        <template #header>
                            <span>财务信息</span>
                        </template>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="账户名称" prop="financeName">
                                    <el-input v-model="customerForm.financeName" placeholder="请输入账户名称" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="纳税人识别号" prop="taxpayerNumber">
                                    <el-input v-model="customerForm.taxpayerNumber" placeholder="请输入纳税人识别号" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="银行账户" prop="bankAccount">
                                    <el-input v-model="customerForm.bankAccount" placeholder="请输入银行账户" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="开户银行" prop="accountBank">
                                    <el-input v-model="customerForm.accountBank" placeholder="请输入开户银行" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="开户行地址" prop="bankAddress">
                                    <el-input v-model="customerForm.bankAddress" placeholder="请输入开户行地址" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <!-- 上传附件 -->
                    <el-card style="margin-bottom: 20px;">
                        <template #header>
                            <span>上传附件</span>
                        </template>
                        <div style="margin-bottom: 16px;">
                            <el-upload ref="uploadRef" :action="uploadAction" :headers="uploadHeaders"
                                :file-list="fileList" :on-success="handleUploadSuccess" :on-remove="handleRemove"
                                :before-upload="beforeUpload" :limit="10" multiple drag>
                                <el-icon class="el-icon--upload">
                                    <UploadFilled />
                                </el-icon>
                                <div class="el-upload__text">
                                    将文件拖到此处，或<em>点击上传</em>
                                </div>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        您可以上传doc, pdf, rar等格式的文件,单个文件上传最大200MB。
                                    </div>
                                </template>
                            </el-upload>
                        </div>
                        <div v-if="fileList.length > 0" style="margin-top: 16px;">
                            <div v-for="(file, index) in fileList" :key="file.uid || index"
                                style="display: flex; align-items: center; justify-content: space-between; padding: 8px 12px; margin-bottom: 8px; background-color: #f5f7fa; border-radius: 4px;">
                                <el-link :href="file.url" target="_blank" type="primary" :underline="false">
                                    {{ file.name }}
                                </el-link>
                                <el-button type="danger" size="small" @click="handleRemoveFile(index)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </el-card>
                </el-form>
            </el-main>
        </el-container>

        <!-- 部门选择对话框 -->
        <el-dialog v-model="showOrgDialog" title="选择部门" width="600px">
            <div style="margin-bottom: 16px;">
                <el-input v-model="orgSearchText" placeholder="搜索部门名称" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <el-tree ref="orgTreeRef" :data="organizationTree" node-key="organizationId" :props="orgTreeProps"
                highlight-current default-expand-all :expand-on-click-node="false" :filter-node-method="filterOrgNode"
                :current-node-key="customerForm.organizationId" @node-click="handleSelectOrg"
                style="max-height: 400px; overflow: auto;" />
        </el-dialog>

        <!-- 用户选择对话框 -->
        <el-dialog v-model="showUserDialog" title="选择用户" width="400px">
            <div style="margin-bottom: 16px;">
                <el-input v-model="userSearchText" placeholder="搜索用户名称" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <el-table :data="filteredUserList" @row-click="handleSelectUser" style="cursor: pointer;">
                <el-table-column prop="userName" label="用户名称" />
            </el-table>
        </el-dialog>

        <!-- 固定底部保存按钮 -->
        <div class="fixed-footer">
            <div class="footer-content" style="float: right;">
                <el-button @click="router.push('/GetCustomer')">关闭</el-button>
                <el-button @click="">取消</el-button>
                <el-button type="primary" @click="updateCustomer" :loading="saving">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Delete, Search, UploadFilled } from '@element-plus/icons-vue'
import myaxios from '@/http/MyAxios'
import moment from 'moment'

const route = useRoute()
const router = useRouter()

// 表单引用
const customerFormRef = ref<FormInstance>()

// 表单数据
const customerForm = reactive({
    customerId: '',
    customerCode: '',
    customerName: '',
    industryId: '',
    customerSourceId: '',
    customerContact: '',
    contactPhone: '',
    customerEmail: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    customerState: 0,
    contactAddress: '',
    customerNote: '',
    // 财务信息
    financeId: '',
    financeName: '',
    taxpayerNumber: '',
    bankAccount: '',
    accountBank: '',
    bankAddress: '',
    // 操作信息
    createor: '',
    createrTime: '',
})

// 表单验证规则
const rules = {
    customerName: [
        { required: true, message: '请输入客户名称', trigger: 'blur' }
    ],
    industryId: [
        { required: true, message: '请选择所属行业', trigger: 'change' }
    ],
    customerSourceId: [
        { required: true, message: '请选择客户来源', trigger: 'change' }
    ],
}

// 接口类型定义
interface IndustryItem {
    industryId: string | number
    industryName: string
}

interface CustomerSourceItem {
    customerSourceId: string | number
    customerSourceName: string
}

interface OrganizationItem {
    organizationId: string | number
    organizationName: string
    organizationCode?: string
    children?: OrganizationItem[]
}

interface UserItem {
    userId: string | number
    userName: string
    userCode?: string
    organizationId?: string | number
    organizationid?: string | number
    orgId?: string | number
    orgid?: string | number
    organizationName?: string
}

// 下拉列表数据
const industryList = ref<IndustryItem[]>([])
const customerSourceList = ref<CustomerSourceItem[]>([])
const organizationTree = ref<OrganizationItem[]>([])
const orgTreeProps = { label: 'organizationName', children: 'children' }
const userList = ref<UserItem[]>([])

// 对话框显示状态
const showOrgDialog = ref(false)
const showUserDialog = ref(false)
const saving = ref(false)
const userSearchText = ref('')
const orgSearchText = ref('')
const orgTreeRef = ref()

// 文件上传
const uploadAction = ref('api/Customer/UploadFile')
const uploadHeaders = ref({})
const fileList = ref<Array<{ name: string; url: string; uid?: number; raw?: File }>>([])

const filterOrgNode = (value: string, data: OrganizationItem) => {
    if (!value) return true
    return data.organizationName?.toLowerCase().includes(value.toLowerCase())
}

watch(orgSearchText, (val) => {
    if (orgTreeRef.value?.filter) {
        orgTreeRef.value.filter(val)
    }
})

const getUserOrgId = (user: UserItem) =>
    user.organizationId ?? user.organizationid ?? user.orgId ?? user.orgid ?? ''

// 过滤用户列表（限定在所选部门）
const filteredUserList = computed(() => {
    const orgId = customerForm.organizationId
    if (!orgId) return []
    const keyword = userSearchText.value?.toLowerCase() || ''
    return userList.value.filter(user => {
        const matchOrg = String(getUserOrgId(user)) === String(orgId)
        const matchKeyword = !keyword || user.userName?.toLowerCase().includes(keyword)
        return matchOrg && matchKeyword
    })
})

const isRootDictionary = (item: any) =>
    !item.parentId || item.parentId === 0 || item.parentId === '0' || item.parentId === null

const matchDictionary = (item: any, names: string[], codes: string[]) => {
    const name = (item.dictionaryName || '').toLowerCase()
    const code = (item.dictionaryCode || '').toLowerCase()
    return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
        codes.some(c => code === c.toLowerCase())
}

const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
    const commonParams = { Pageindex: 1, PageSize: 1000 }
    try {
        const listRes = await myaxios.get('/api/Dictionary/GetDictionaryList', { params: commonParams })
        const list = listRes.data?.data?.data || []
        const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
        if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
        console.warn('获取字典列表失败', error)
    }

    for (const name of nameCandidates) {
        try {
            const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
            })
            const list = res.data?.data?.data || []
            const found = list.find((item: any) => isRootDictionary(item))
            if (found?.dictionaryId) return found.dictionaryId
        } catch (error) {
            console.warn(`按名称 ${name} 获取字典失败`, error)
        }
    }
    return null
}

const fetchDictionaryChildren = async (parentId: string | number | null) => {
    if (!parentId) return []
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
            params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
        })
        return res.data?.data?.data || []
    } catch (error) {
        console.warn('获取字典子项失败', error)
        return []
    }
}

const loadIndustryList = async () => {
    const parentId = await findDictionaryParentId(['所属行业', '行业'], ['industry'])
    const children = await fetchDictionaryChildren(parentId)
    industryList.value = children.map((item: any) => ({
        industryId: item.dictionaryId,
        industryName: item.dictionaryName
    }))
}

const loadCustomerSourceList = async () => {
    const parentId = await findDictionaryParentId(['客户来源'], ['customersource', 'customer_source'])
    const children = await fetchDictionaryChildren(parentId)
    customerSourceList.value = children.map((item: any) => ({
        customerSourceId: item.dictionaryId,
        customerSourceName: item.dictionaryName
    }))
}

// 转换部门树数据
const transformOrgTree = (nodes: any): OrganizationItem[] => {
    if (!nodes) return []
    const list = Array.isArray(nodes) ? nodes : [nodes]
    return list.map((item: any) => ({
        organizationId: item.organizationId ?? item.organizationid ?? item.id ?? item.orgId ?? item.orgid ?? '',
        organizationName: item.organizationName ?? item.organizationname ?? item.label ?? item.name ?? '',
        organizationCode: item.organizationCode ?? item.organizationcode ?? item.code,
        children: transformOrgTree(
            item.children ??
            item.childrens ??
            item.childList ??
            item.childNodes ??
            item.childs ??
            item.nodes ??
            []
        )
    }))
}

// 获取部门树
const getOrganizationTree = () => {
    myaxios.get('api/Organization/GetOrganizationTree', { params: { parentid: 0 } }).then((res: any) => {
        const payload = Array.isArray(res.data) ? res.data : res.data?.data ?? res.data?.datas ?? []
        organizationTree.value = transformOrgTree(payload)
    }).catch((err: any) => {
        console.error('获取部门树失败:', err)
        organizationTree.value = []
    })
}

// 获取用户列表
const getUserList = () => {
    myaxios.get('api/Supplier/GetUser').then((res: any) => {
        if (res.data.code === 200) {
            userList.value = res.data.data || []
        }
    }).catch((err: any) => {
        console.error('获取用户列表失败:', err)
    })
}

// 打开部门选择对话框
const openOrgDialog = () => {
    orgSearchText.value = ''
    showOrgDialog.value = true
}

// 打开用户选择对话框
const openUserDialog = () => {
    if (!customerForm.organizationId) {
        ElMessage.warning('请先选择销售部门')
        return
    }
    userSearchText.value = ''
    showUserDialog.value = true
}

// 选择部门
const handleSelectOrg = (row: OrganizationItem) => {
    customerForm.organizationId = String(row.organizationId)
    customerForm.organizationName = row.organizationName
    customerForm.userId = ''
    customerForm.userName = ''
    showOrgDialog.value = false
}

// 选择用户
const handleSelectUser = (row: UserItem) => {
    customerForm.userId = String(row.userId)
    customerForm.userName = row.userName
    showUserDialog.value = false
}

// 文件上传前验证
const beforeUpload = (file: File) => {
    const isValidType = ['application/msword', 'application/pdf', 'application/x-rar-compressed',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
        .includes(file.type) || file.name.endsWith('.doc') || file.name.endsWith('.pdf') ||
        file.name.endsWith('.rar') || file.name.endsWith('.docx')
    const isLt200M = file.size / 1024 / 1024 < 200

    if (!isValidType) {
        ElMessage.error('只能上传doc, pdf, rar格式的文件!')
        return false
    }
    if (!isLt200M) {
        ElMessage.error('文件大小不能超过200MB!')
        return false
    }
    return true
}

// 文件上传成功
const handleUploadSuccess = (response: any, file: any) => {
    if (response && response.code === 200) {
        ElMessage.success('文件上传成功')
        if (response.data?.url && file) {
            const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
            if (index > -1 && fileList.value[index]) {
                fileList.value[index].url = response.data.url
            }
        }
    } else {
        ElMessage.error(response?.message || '文件上传失败')
    }
}

// 移除文件
const handleRemove = (file: any) => {
    const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
    if (index > -1) {
        fileList.value.splice(index, 1)
    }
}

// 手动移除文件
const handleRemoveFile = (index: number) => {
    fileList.value.splice(index, 1)
    ElMessage.success('文件已移除')
}

// 应用缓存数据到表单（立即显示）
const applyCachedData = (data: any) => {
    if (!data) return

    // 填充表单数据
    Object.assign(customerForm, {
        customerId: data.customerId || '',
        customerCode: data.customerCode || '',
        customerName: data.customerName || '',
        industryId: data.industryId || '',
        customerSourceId: data.customerSourceId || '',
        customerContact: data.customerContact || '',
        contactPhone: data.contactPhone || '',
        customerEmail: data.customerEmail || '',
        organizationId: data.organizationId || '',
        organizationName: data.organizationName || '',
        userId: data.userId || '',
        userName: data.userName || '',
        customerState: data.customerState ?? 0,
        contactAddress: data.contactAddress || '',
        customerNote: data.customerNote || '',
        // 财务信息
        financeId: data.financeId || '',
        financeName: data.financeName || '',
        taxpayerNumber: data.taxpayerNumber || '',
        bankAccount: data.bankAccount || '',
        accountBank: data.accountBank || '',
        bankAddress: data.bankAddress || '',
    })
}

// 获取客户详情
const getCustomerDetail = () => {
    const customerId = route.query.customerId
    if (!customerId) {
        ElMessage.error('客户ID不能为空')
        router.push('/GetCustomer')
        return
    }

    myaxios.get(`api/Customer/GetCustomerById?customerId=${customerId}`).then((res: any) => {
        if (res.data.code === 200) {
            const data = res.data.data
            // 填充表单数据（使用后端返回的最新数据）
            applyCachedData(data)

            // 如果有附件信息，填充文件列表
            if (data.files && Array.isArray(data.files)) {
                fileList.value = data.files.map((file: any) => ({
                    name: file.fileName,
                    url: file.fileUrl,
                    uid: file.fileId
                }))
            }

            // 清除缓存
            sessionStorage.removeItem('customer_edit_cache')
        } else {
            ElMessage.error(res.data.message || '获取客户详情失败')
            router.push('/GetCustomer')
        }
    }).catch((err: any) => {
        console.error('获取客户详情失败:', err)
        // 即使后端请求失败，也不跳转，保留缓存数据显示
        ElMessage.warning('获取最新数据失败，当前显示的是缓存数据')
    })
}

// 更新客户信息
const updateCustomer = async () => {
    if (!customerFormRef.value) return

    try {
        await customerFormRef.value.validate()
        saving.value = true
        
        // 自动设置操作人和操作时间 - 从后端获取真实姓名
        let currentUser = localStorage.getItem('username') || ''
        try {
            const res = await myaxios.get('/api/User/GetMyProfile')
            const droot: any = res?.data ?? {}
            const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
            if (d) {
                // 优先使用真实姓名，其次用户名
                currentUser = d.userName || d.realName || d.nickname || currentUser
                // 更新localStorage以便后续使用
                if (currentUser) {
                    localStorage.setItem('username', currentUser)
                }
            }
        } catch (error) {
            console.warn('获取当前用户信息失败，使用本地存储的值:', error)
        }
        const currentTime = moment().format('YYYY-MM-DD HH:mm:ss')

        // 更新表单数据中的操作人和操作时间
        customerForm.createor = currentUser
        customerForm.createrTime = currentTime

        const updateData = {
            ...customerForm,
            createor: currentUser,
            createrTime: currentTime,
            files: fileList.value.map(file => ({
                fileName: file.name,
                fileUrl: file.url
            }))
        }

        myaxios.put('/api/Customer/UpdateCustomerWithFinance', updateData).then((res: any) => {
            if (res.data.code === 200) {
                ElMessage.success('客户信息更新成功')
                router.push('/GetCustomer')
            } else {
                ElMessage.error(res.data.message || '更新失败')
            }
        }).catch((err: any) => {
            console.error('更新客户信息失败:', err)
            ElMessage.error('更新客户信息失败')
        }).finally(() => {
            saving.value = false
        })
    } catch (error) {
        console.error('表单验证失败:', error)
        saving.value = false
    }
}

// 初始化数据
onMounted(() => {
    const CUSTOMER_EDIT_CACHE_KEY = 'customer_edit_cache'

    // 并行加载基础数据和客户详情
    Promise.allSettled([
        loadIndustryList(),
        loadCustomerSourceList(),
        getOrganizationTree(),
        getUserList()
    ])

    // 先从缓存读取数据，立即填充表单（实现无延迟显示）
    try {
        const cachedData = sessionStorage.getItem(CUSTOMER_EDIT_CACHE_KEY)
        if (cachedData) {
            const parsedData = JSON.parse(cachedData)
            applyCachedData(parsedData)
            // 清除缓存标记，但不删除数据，等后端数据返回后再清除
        }
    } catch (error) {
        console.warn('读取缓存数据失败:', error)
    }

    // 同时从后端获取最新数据（后台更新）
    getCustomerDetail()
})
</script>

<style scoped>
.common-layout {
    padding: 20px;
    position: relative;
}

.el-card {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.el-form-item {
    margin-bottom: 22px;
}

.el-upload__tip {
    color: #606266;
    font-size: 12px;
    margin-top: 7px;
}

.fixed-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 1px solid #e4e7ed;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.footer-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 16px 20px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>